<?php
/**
 * cms内容管理
 * @since   2019-11-30
 * @author  曾
 */

namespace app\admin\controller;


use app\model\CmsContent;
use app\util\ReturnCode;
use app\model\FilesManage; // 附件管理数据表
use app\model\CmsTags; // tag标签数据表
use app\model\CmsTagData; // tag标签和文档对应关系数据表
use app\util\Tools;
use think\Request;
use traits\controller\Jump;

class CmsContentList extends Base {

    /**
     * 获取内容列表
     * @return array
     * @throws \think\exception\DbException
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function index() {
        $limit = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $classid = $this->request->get('classid', '');
        $title = $this->request->get('title', '');
        $hide = $this->request->get('hide', '');

        $obj = new CmsContent();
        if (strlen($classid)) {
            $obj = $obj->where('classid', $classid);
        }
        if (strlen($hide)) {
            $obj = $obj->where('hide', $hide);
        }
        $obj = $obj->whereLike('title', "%{$title}%");
        // 模糊查询加排序
        $listObj = $obj->order('newtime DESC')
            ->paginate($limit, false, ['page' => $start])->toArray();

        return $this->buildSuccess([
            'list'  => $listObj['data'],
            'count' => $listObj['total']
        ], '获取成功');
    }

    /**
     * 新增内容
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function add() {
        $postData = $this->request->post();
       /* $this->debug($postData);
        if (Request::instance()->isPost()){
            $this->debug(dump($postData)."当前为 POST 请求");
        }*/
        /*if ($postData['url']) {
            $postData['url'] = 'admin/' . $postData['url'];
        }*/
        $res = new CmsContent($postData);
        // 过滤post数组中的非数据表字段数据
        $res->allowField(true)->save();
        // $res = CmsContent::create($postData);
        // 新增成功后 把对应的缩略图改成引用状态
        $fileId = $this->request->post('headimgid');
        FilesManage::update([
            'id'   => $fileId,
            'iscite' => 1
        ]);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            // 新增成功后 改变tag
            $tagName = $this->request->post('tagname'); // id集合
            if ($tagName <> "[]") {
                $tagNames = json_decode($tagName,true); // json字符串转数组 使用 json_decode($d, true)。
                for( $i=0; $i<count($tagNames); $i++){
                    if($tagNames[$i]){
                        // 根据tagname 获取tagid
                        $data = CmsTags::get(['name' => $tagNames[$i]]);
                        $id = $data->id;
                        $tagdata = new CmsTagData;
                        $tagdata->data([
                            'tagid'  =>  $id,
                            'classid' => $this->request->post('classid'),
                            'id' => $res -> id
//                        'createTime' => date('Y-m-d H:i:s', time())
                        ]);
                        $tagdata->save();
                    }
                }
            }
            //  改变tag end
            return $this->buildSuccess([]);
        }
    }

    /**
     * 编辑内容
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function edit() {
        $postData = $this->request->post();
        $res = new CmsContent();
        // 过滤post数组中的非数据表字段数据
        $res->allowField(true)->save($postData,['id' => $postData['id']]);
        // 新增成功后 把对应的缩略图改成引用状态1
        $fileId = $this->request->post('headimgid');
        FilesManage::update([
            'id'   => $fileId,
            'iscite' => 1
        ]);
        // 如果更改了缩略图 则把之前缩略图 引用改成0
        if ($postData['headimgidBefore'] <> $fileId) {
            FilesManage::update([
                'id'   => $postData['headimgidBefore'],
                'iscite' => 0
            ]);
        }
        // 如果更改了tag 对比之后进行相关操作
        $tagName = $this->request->post('tagname'); // id集合
        // 删除文章对应tag记录 CmsTagData
        CmsTagData::where('id',$postData['id'])->delete();
        // 新增
        if ($tagName <> "[]") {
            $tagNames = json_decode($tagName,true); // json字符串转数组 使用 json_decode($d, true)。
            for( $i=0; $i<count($tagNames); $i++){
                if($tagNames[$i]){
                    // 根据tagname 获取tagid
                    $data = CmsTags::get(['name' => $tagNames[$i]]);
                    $id = $data->id;
                    $tagdata = new CmsTagData;
                    $tagdata->data([
                        'tagid'  =>  $id,
                        'classid' => $this->request->post('classid'),
                        'id' => $res -> id
//                        'createTime' => date('Y-m-d H:i:s', time())
                    ]);
                    $tagdata->save();
                }
            }
        }
        //  改变tag end
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }

    /**
     * 删除内容
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function del() {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        // 根据id 查缩略图id
        $data = CmsContent::get($id);
        $fileId = $data->headimgid;
        // 查所有符合缩略图id 的数据
        $listObj = CmsContent::all(['headimgid'=>$fileId]);
//        $this->debug($listObj);
//        $this->debug(count($listObj));
        // 如果数据>=2条 则不改变图片引用状态 否则改变为未引用
        if (count($listObj) < 2) {
            FilesManage::update([
                'id'   => $fileId,
                'iscite' => 0
            ]);
        }
        CmsContent::destroy($id);
        // 删除文章对应tag记录 CmsTagData
        CmsTagData::where('id',$id)->delete();
        return $this->buildSuccess([]);
    }

    /**
     * 内容状态编辑 显示/隐藏
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function changeStatus() {
        $id = $this->request->get('id');
        $status = $this->request->get('status');
        $res = CmsContent::update([
            'id'   => $id,
            'hide' => $status
        ]);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }

    /**
     * 内容归档
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function archive() {
        $id = $this->request->get('id');
        $status = $this->request->get('isdel');
        $res = CmsContent::update([
            'id'   => $id,
            'isdel' => $status
        ]);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }
    /**
     * 获取内容
     * @return array
     * @throws \think\exception\DbException
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function detail() {
        $id = $this->request->get('id');
        $listObj = CmsContent::get(['id' => $id]);
        if($listObj){
            return $this->buildSuccess($listObj,'获取详情成功');
        }else{
            return $this->buildFailed(ReturnCode::NOT_EXISTS,'当前内容不存在');
        }
    }

    /**
     * CMS图片文件上传 ck
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function upload() {
        $path = '/upload/cms/' . date('Ymd', time()) . '/';
        $name = $_FILES['upload']['name'];
        $fileType = pathinfo($name,PATHINFO_EXTENSION);
        // 文件类型type
        $CmsUtil = new CmsUtil();
        $typeArr = $CmsUtil->filesType();
        $flag = false;
        for($i=0; $i<count($typeArr);$i++) {
            if($fileType === $typeArr[$i]){
                $flag = true;
                break;
            } else {
                $flag = false;
            }
        }
        if(!$flag) {
            $dataR{"uploaded"} = 0;
            $dataR{"error"}{"message"} = '文件类型不正确';
            return $dataR;
        }
        $tmp_name = $_FILES['upload']['tmp_name'];
        $error = $_FILES['upload']['error'];
        //过滤错误
        if ($error) {
            switch ($error) {
                case 1 :
                    $error_message = '您上传的文件超过了PHP.INI配置文件中UPLOAD_MAX-FILESIZE的大小';
                    break;
                case 2 :
                    $error_message = '您上传的文件超过了PHP.INI配置文件中的post_max_size的大小';
                    break;
                case 3 :
                    $error_message = '文件只被部分上传';
                    break;
                case 4 :
                    $error_message = '文件不能为空';
                    break;
                default :
                    $error_message = '未知错误';
            }
            die($error_message);
        }
        $arr_name = explode('.', $name);
        $hz = array_pop($arr_name);
        $new_name = md5(time() . uniqid()) . '.' . $hz;
        if (!file_exists($_SERVER['DOCUMENT_ROOT'] . $path)) {
            mkdir($_SERVER['DOCUMENT_ROOT'] . $path, 0755, true);
        }
        if (move_uploaded_file($tmp_name, $_SERVER['DOCUMENT_ROOT'] . $path . $new_name)) {
            if($fileType === 'jpg' || $fileType === 'jpeg' || $fileType === 'gif' || $fileType === 'bmp' || $fileType === 'png') {
                // 获取图片属性
                $fileSrc = '.' . $path . $new_name;
                $image = \think\Image::open($fileSrc);
                // 返回图片的宽度
                $width = $image->width() . 'px';
                // 返回图片的高度
                $height = $image->height() . 'px';
                // 返回图片的类型
                $type = $image->type();
                // 返回图片的mime类型
//            $mime = $image->mime();
                // 返回图片的大小
                $size = filesize($fileSrc);
                $kb = 1024;
                $mb = 1024 * $kb;
                $gb = 1024 * $mb;
                if ($size < $kb) {
                    $size =  $size . "B";
                } elseif ($size < $mb) {
                    $size = round($size / $kb, 2) . "KB";
                } elseif ($size < $gb) {
                    $size = round($size / $mb, 2) . "MB";
                }
                // 保存到数据库 FilesManage
                $isheadimg = (int)$this->request->header('isheadimg', 0);
                $files = new FilesManage;
                // 模型对象赋值
                $files->data([
                    'filename'  =>  $new_name,
                    'url' =>  $path . $new_name,
                    'imgwidth' => $width,
                    'imgheight' => $height,
                    'filetype' => $type,
                    'filesize' => $size,
                    'isheadimg' => $isheadimg,
                    'userid' => $this->request->header('userid', ''),
                    'username' => $this->request->header('username', ''),
                    'createTime' => date('Y-m-d H:i:s', time())
                ]);
                $files->save();
                $fileId = $files->id;// 获取新增数据的id
            }

            $dataR{"uploaded"} =1;
            $dataR{"fileName"} = $new_name;
            if($isheadimg === 1) {
                $dataR{"url"} = $path . $new_name;
            } else {
                $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';

                $dataR{"url"} = $http_type.$_SERVER['HTTP_HOST'].$path . $new_name;
            }
            $dataR{"headimgid"} = $fileId;
        } else {
            $dataR{"uploaded"} =0;
            $err{"message"} = '文件上传异常';
            $dataR{"error"} = $err;
        }
        return $dataR;
    }

    /**
     * CMS文件上传
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function fileUpload() {
        $path = '/upload/cms/file/' . date('Ymd', time()) . '/';
        $name = $_FILES['file']['name'];
        $tmp_name = $_FILES['file']['tmp_name'];
        $error = $_FILES['file']['error'];
        //过滤错误
        if ($error) {
            switch ($error) {
                case 1 :
                    $error_message = '您上传的文件超过了PHP.INI配置文件中UPLOAD_MAX-FILESIZE的大小';
                    break;
                case 2 :
                    $error_message = '您上传的文件超过了PHP.INI配置文件中的post_max_size的大小';
                    break;
                case 3 :
                    $error_message = '文件只被部分上传';
                    break;
                case 4 :
                    $error_message = '文件不能为空';
                    break;
                default :
                    $error_message = '未知错误';
            }
            die($error_message);
        }
        $arr_name = explode('.', $name);
        $hz = array_pop($arr_name);
        $new_name = md5(time() . uniqid()) . '.' . $hz;
        if (!file_exists($_SERVER['DOCUMENT_ROOT'] . $path)) {
            mkdir($_SERVER['DOCUMENT_ROOT'] . $path, 0755, true);
        }
        if (move_uploaded_file($tmp_name, $_SERVER['DOCUMENT_ROOT'] . $path . $new_name)) {
            // 获取图片属性
            $fileSrc = '.' . $path . $new_name;
//            $this ->debug('++++'.$_FILES['file']);
//            dump($fileSrc);
            // 获取新增数据的id
            return $this->buildSuccess([
                'fileName' => $new_name,
//                'fileUrl'  => $this->request->domain() . $path . $new_name,
                'fileUrl'  => $path . $new_name,
            ]);
        } else {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, '文件上传异常');
        }
    }
}
